import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/page/Login/login'
import Main from '@/page/main/main'
// import Comment from '@/page/sys/comment.vue'
import Song from '@/page/sys/song.vue'

import SongAdd from '@/components/song/songadd.vue'
import SongEdit from '@/components/song/songedit.vue'
import SongInfo from '@/components/song/songinfo.vue'

import Role from '@/page/sysuser/Role.vue';
import Menu from '@/page/sysuser/Menu.vue';
import User from '@/page/sysuser/User.vue';
import SysIndex from '@/page/sysuser/Index.vue';

import request from "../axios";

import collect from '../page/sys/collect.vue'

import store from "../store"

Vue.use(VueRouter)


// 解决路由重复问题
//获取原型对象上的push函数
const originalPush = VueRouter.prototype.push
//修改原型对象中的push方法
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => {
    // err
    // 将报错的信息catch??
    // console.log(err);
  })
}

const router = new VueRouter({
  routes: [
    {
      path: '/main',
      name: 'main',
      component: Main,
      children: [
        {
          path: '/Index',
          name: 'Index',
          // component: Main   // 按需引入
          component: () => import('@/page/main/index.vue')   // 按需引入
        },
        {
          path: '/Banner',
          name: 'Banner',
          component: () => import('@/page/sys/banner.vue'),   // 按需引入
          // component: () => import('@/components/banner/bannermain.vue'),   // 按需引入
          children: [
            {
              path: 'main',
              name: 'BannerMain',
              component: () => import('@/components/banner/bannermain.vue')   // 按需引入
            },
            {
              path: 'info',
              name: 'ShowBanner',
              component: () => import('@/components/banner/bannershow.vue')   // 按需引入
            }
          ]
        },

        {
          path: '/member',
          name: 'member',
          component: () => import('@/page/member')
        },

				{
				  path: '/Singer',
				  name: 'Singer',
				  component: () => import('@/page/sys/Singer.vue')
				},
        {
          path: '/collect',
          name: 'collect',
          component:collect
        },
        // {
        //   path: '/Comment',
        //   name: '/Comment',
        //   component: Comment,   // 按需引入
        //
        // },
        // 歌曲模块
        {
          path: '/Song',
          name: 'Song',
          component: Song,
          children: [
            {
              path: 'add',
              name: 'SongAdd',
              component: SongAdd,
            },
            {
              path: 'edit',
              name: 'SongEdit',
              component: SongEdit,
            },
            {
              path: 'info',
              name: 'SongInfo',
              component: SongInfo,
            }
          ]
        },
        // 系统管理
        // 歌曲模块
        {
          path: '/Sys',
          name: 'Sys',
          component: SysIndex,
          children: [
            {
              path: 'user',
              name: 'user',
              component: User,
            },
            {
              path: 'menu',
              name: 'menu',
              component: Menu,
            },
            {
              path: 'role',
              name: 'role',
              component: Role,
            },
          ]
        },

      ]
    }
    ,
    {
      path: '/login',
      name: 'Login',
      component: Login   // 直接引入
    }
    ]
})


// // 路由前置守卫
// //路由跳转前执行beforeEach中代码
// router.beforeEach( (to, from, next)=> {
//   console.log(to)
//   console.log("目标路由地址为:", to.fullPath);
//   console.log("源路由地址为:", from.fullPath);
//
//   // let regex = /^[/]main.*$/;
//   let regex = /^[/]login.*$/; // 是到登录页的话就放行
//   if (!regex.test(to.fullPath)) {
//     if(to.fullPath=="/" || to.fullPath == "") {
//       router.push('/login')
//     }
//
//     console.log("验证用户是否登录" + to.fullPath);
//     // 发送请求查询是否token有效，
//     // request.get('/MannagerServlet?method=checkToken')
//     //     .then((res)=> {
//     //       console.log("已登录用户");
//           next();//放行。
//     //     })
//     //     .catch((err)=> {
//     //       router.push('/login')
//     //     })
//   } else {  // 到登录页
//     next();//放行。
//
//     // 验证登录直接返回到首页
//     // request.get('/MannagerServlet?method=checkToken')
//     //   .then((res)=> {
//     //     router.push('/index')
//     //   })
//     //   .catch((err)=> {
//     //
//     //   })
//     // console.log("不验证用户是否登录")
//   }
// });


// 动态路由处理
router.beforeEach( (to, from, next)=> {
  // 获取权限路由
  let hasRoute = store.state.menus.hasRoutes

  // 获取token
  let token = localStorage.getItem("access_token")

  // 判断是否时登录请求，登录请求直接放行
  if(to.fullPath == "/login") {
    next();
    return;
  }

  if(!token) { // 没有token需要登录
    next({path: '/login'});
    return;
  }

  if(!hasRoute) { // 路由没有权限存储，就请求获取权限
    request.get("/sys/menu/nav").then(res => {
      console.log("获取的路由信息");
      console.log(res.data.data)

      // 拿到menuList
      store.commit("setMenuList", res.data.data.nav)

      // 拿到用户权限
      store.commit("setPermList", res.data.data.authoritys)

      console.log(store.state.menus.menuList)

      // 动态绑定路由
      let newRoutes = router.options.routes

      res.data.data.nav.forEach(menu => {
        console.log("当前导航处理的是：" + menu.title);
        if (menu.children && menu.children.length > 0) {
          console.log(menu.title+"进来了");
          menu.children.forEach(e => {
            // 转成路由
            let route = menuToRoute(e)

            // 吧路由添加到路由管理中
            if (route) {
              // newRoutes[0].children.push(route)
              newRoutes[0].children.push(route)
            }
          })
        } else { // 目录即导航标签。
          console.log(menu.title+"进来了");
          console.log("评论添加：" + JSON.stringify(menu));
          let route = menuToRoute(menu)
          if (route) {
            newRoutes[0].children.push(route)
          }
        }
      })

      console.log("newRoutes")
      console.log(newRoutes)
      router.addRoutes(newRoutes) //添加路由
      hasRoute = true
      store.commit("changeRouteStatus", hasRoute)
    })
  }

  next();
})

// 导航转成路由
const menuToRoute = (menu) => {

  if (!menu.component) {
    return null
  }

  let route = {
    // name: menu.name,
    name: menu.path,
    path: menu.path,
    meta: {
      icon: menu.icon,
      title: menu.title
    }
  }
  route.component = () => import('@/' + menu.component +'.vue')

  return route
}


export default router
